import { Page, Application } from "maishu-chitu";
import { isWeixin } from "./services/weixinService";
import React = require("react");
import { ComponentData } from "maishu-jueying";
import { ComponentInfo } from "components/common/component";
import { createService } from "components/common/base-component";
import { LocalService } from "./services/localService";
import websiteConfig = require("json!websiteConfig");


import { Component } from "maishu-jueying";
import { ComponentContainer } from "../components/component-container";
import { MasterPage } from "components/common/master-page";

Component.register(ComponentContainer.name, ComponentContainer);
Component.register(MasterPage.name, MasterPage);

let contextName = websiteConfig.stationPath;
// import { MyComponentData } from "models";

// export function defaultNavBar(element: HTMLElement,
//     options?: { title?: string, right?: JSX.Element, showBackButton?: boolean });
// export function defaultNavBar(elementPage: Page,
//     options?: { title?: string, right?: JSX.Element, showBackButton?: boolean });
export function defaultNavBar(elementPage: Page,
    options?: { title?: string, right?: JSX.Element, showBackButton?: boolean }) {
    //=============================
    // window[ADMIN_APP] 表明为设计时
    // if (window[ADMIN_APP]) {
    //     return null;
    // }
    //=============================

    // let element: HTMLElement;
    // if ((elementPage as Page).element != null) {
    let element = elementPage.element;
    let app = elementPage.app as Application;
    // }
    // else {
    //     element = elementPage;
    // }


    if (isWeixin) {
        return weixinNavheader(element, options);
    }

    // document.title = options.title || "";
    options = options || {};
    let title = options.title || '';
    let className = element.className;
    if (className.indexOf("topbar-padding") < 0)
        element.className = className + ' topbar-padding';

    return (
        <nav className="bg-primary">
            <div className="pull-left" style={{ padding: 0, width: 60 }}>
                {options.showBackButton == false ?
                    <span dangerouslySetInnerHTML={{ __html: "&nbsp;" }}></span> :
                    <button name="back-button" className="left-button" style={{ opacity: 1 }} onClick={() => app.back()}>
                        <i className="icon-chevron-left"></i>
                    </button>
                }
                {/* {options.left} */}
            </div>
            <div className="pull-right" style={{ padding: 0, width: 60 }}>
                {options.right ? options.right :
                    <span dangerouslySetInnerHTML={{ __html: "&nbsp;" }}></span>}
            </div>
            <div className="" style={{ padding: 0 }}>
                <h4>
                    {title}
                </h4>
            </div>
        </nav>
    );
}

function weixinNavheader(element: HTMLElement, options?: { title?: string, right?: JSX.Element, left?: JSX.Element });
function weixinNavheader(elementPage: Page, options?: { title?: string, right?: JSX.Element, left?: JSX.Element })
function weixinNavheader(elementPage: any, options?: { title?: string, right?: JSX.Element, left?: JSX.Element }) {

    let element: HTMLElement;
    if ((elementPage as Page).element != null) {
        element = (elementPage as Page).element;
    }
    else {
        element = elementPage;
    }

    document.title = options.title || "";
    if (options.left == null && options.right == null)
        return null;

    let className = element.className;
    if (className.indexOf("topbar-padding") < 0)
        element.className = className + ' topbar-padding';

    return (
        <nav className="bg-primary">
            <div className="col-xs-3" style={{ padding: 0 }}>
                {options.left}
            </div>
            <div className="col-xs-6" style={{ padding: 0 }}>

            </div>
            <div className="col-xs-3" style={{ padding: 0 }}>
                {options.right ? (options.right) : null}
            </div>
        </nav>
    );

}

/** 加载 pageData 中的组件 */
export async function loadComponents(pageData: ComponentData) {
    let componentInfos: ComponentInfo[] = [];
    let stack = [pageData];

    let componentPaths = await getComponentInfos();
    while (stack.length > 0) {
        let item = stack.pop() as ComponentData;
        if (item.type == "ComponentContainer") {
            continue;
        }

        let componentPath = componentPaths.filter(o => o.name == item.type)[0]
        if (componentPath) {
            componentInfos.push(componentPath)
        }

        (item.children || []).forEach(c => {
            stack.push(c);
        })
    }

    return Promise.all(componentInfos.map(p => loadComponent(p)));
}

function loadComponent(componentInfo: ComponentInfo): Promise<ComponentInfo[]> {
    return new Promise((resolve, reject) => {
        // let componentInfos: ComponentInfo[] = [];
        requirejs({ context: contextName }, [`${componentInfo.path}`],
            async (mod) => {

                console.assert(componentInfo.name != null);
                console.assert(typeof mod[componentInfo.name] == "function");
                let { Component } = await import("maishu-jueying");
                Component.register(componentInfo.name, mod[componentInfo.name]);

                resolve(componentInfos);
            },
            (err) => {
                reject(err)
            },
        )
    })
}

let componentInfos: ComponentInfo[];
async function getComponentInfos(): Promise<ComponentInfo[]> {
    if (componentInfos != null && componentInfos.length > 0)
        return componentInfos;

    let localService = createService(LocalService);
    componentInfos = await localService.getComponentInfos();
    return componentInfos;
}

export function formatDate(date: Date | string, showHourMinutes?: boolean): string {
    if (typeof date == "string")
        return date;

    let d = date;
    if (showHourMinutes)
        return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()} ${d.getHours() + 1}:${d.getMinutes()}`;

    return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`;
}